package com.ming.common.beetl.util;

import com.ming.common.beetl.entity.BaseEntity;
import com.ming.common.beetl.entity.DataSourceEntity;
import com.ming.common.beetl.entity.IvyDbDatasource;
import com.zaxxer.hikari.HikariDataSource;

public class DataSourceUtil {

    private volatile static DataSourceUtil instance;
    private DataSourceUtil(){ }

    public  static DataSourceUtil NEW() {
        if (instance == null){
            synchronized (DataSourceUtil.class){
                if (instance == null){
                    instance = new DataSourceUtil();
                }
            }
        }
        return instance;
    }

    private BaseEntity dsEntity;
    private IvyDbDatasource ivyDbDatasource;

    public DataSourceUtil baseEntity(BaseEntity dsEntity) {
        this.dsEntity = dsEntity;
        return this;
    }


    public DataSourceUtil ivyDbDatasource(IvyDbDatasource ivyDbDatasource) {
        this.ivyDbDatasource = ivyDbDatasource;
        return this;
    }

    public HikariDataSource build() {
        DataSourceEntity dataSourceEntity = new DataSourceEntity();
        String driverClassName = null;
        String jdbcUrl = null;
        String username = null;
        String password = null;
        if(ivyDbDatasource != null){
            driverClassName = ivyDbDatasource.getDriverClassName();
            jdbcUrl = ivyDbDatasource.getJdbcUrl();
            username = ivyDbDatasource.getUsername();
            password = ivyDbDatasource.getPassword();
        }else{
            driverClassName = dsEntity.getStrValue("driverClassName");
            jdbcUrl = dsEntity.getStrValue("jdbcUrl");
            username = dsEntity.getStrValue("username");
            password = dsEntity.getStrValue("password");
        }
        dataSourceEntity.setDriverClassName(driverClassName);
        dataSourceEntity.setJdbcUrl(jdbcUrl);
        dataSourceEntity.setUsername(username);
        dataSourceEntity.setPassword(password);
        if(ivyDbDatasource != null) {
            return SqlUtil.buildHikariDataSource(dataSourceEntity,ivyDbDatasource);
        }
        return SqlUtil.buildHikariDataSource(dataSourceEntity,dsEntity);
    }
}
